package com.beiji.lib.pen.utils;

import android.graphics.Bitmap;
import android.util.LruCache;

/*
内存缓存工具类
 */
public class LruCacheUtils {
    private static LruCacheUtils instance;

    private LruCache<String, Bitmap> mLruCache;

    public LruCacheUtils() {
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        int cacheSize = maxMemory / 8;
        mLruCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
        };
    }

    public static LruCacheUtils getInstance() {
        if (instance == null) {
            synchronized (LruCacheUtils.class) {
                if (instance == null) {
                    instance = new LruCacheUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 根据key获取缓存图片
     *
     * @param key
     * @return
     */
    public Bitmap getBitmapFromMemCache(int key) {
        return mLruCache.get(String.valueOf(key));
    }

    public void addBitmapToMemoryCache(int key, Bitmap bitmap) {
        if (mLruCache.get(String.valueOf(key)) == null) {
            mLruCache.put(String.valueOf(key), bitmap);
        }
    }

    public boolean isExistKey(int key) {
        return mLruCache.get(String.valueOf(key)) == null ? false : true;
    }
}
